package cn.iocoder.yudao.module.picturebook.service.wechat;

import cn.iocoder.yudao.module.picturebook.config.WechatConfig;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.wechat.WechatToken;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.wechat.WechatUserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class WechatService {

    private final WechatConfig wechatConfig;
    private final ObjectMapper objectMapper;

    public WechatService(WechatConfig wechatConfig, ObjectMapper objectMapper) {
        this.wechatConfig = wechatConfig;
        this.objectMapper = objectMapper;
    }

    /**
     * 使用code换取access_token和openid
     */
    public WechatToken getAccessToken(String code) {
        try {
            // 构建请求URL
            String url = wechatConfig.getTokenUrl() +
                    "?appid=" + wechatConfig.getAppId() +
                    "&secret=" + wechatConfig.getAppSecret() +
                    "&code=" + code +
                    "&grant_type=authorization_code";
            
            // 发送HTTP请求
            String response = sendGetRequest(url);
            
            // 解析JSON响应
            return objectMapper.readValue(response, WechatToken.class);
        } catch (Exception e) {
            throw new RuntimeException("获取微信access_token失败", e);
        }
    }

    /**
     * 使用access_token和openid获取用户信息
     */
    public WechatUserInfo getUserInfo(String accessToken, String openId) {
        try {
            // 构建请求URL
            String url = wechatConfig.getUserinfoUrl() +
                    "?access_token=" + accessToken +
                    "&openid=" + openId +
                    "&lang=zh_CN";
            
            // 发送HTTP请求
            String response = sendGetRequest(url);
            
            // 解析JSON响应
            return objectMapper.readValue(response, WechatUserInfo.class);
        } catch (Exception e) {
            throw new RuntimeException("获取微信用户信息失败", e);
        }
    }

    /**
     * 发送HTTP GET请求
     */
    private String sendGetRequest(String url) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        
        return response.toString();
    }
}